package com.yjkf.zh.admin.service.impl;

import com.yjkf.zh.admin.dao.*;
import com.yjkf.zh.admin.model.*;
import com.yjkf.zh.admin.service.RedisService;
import com.yjkf.zh.admin.service.SysMenuService;
import com.yjkf.zh.admin.service.SysUserService;
import com.yjkf.zh.core.http.HttpResult;
import com.yjkf.zh.core.page.MybatisPageHelper;
import com.yjkf.zh.core.page.PageRequest;
import com.yjkf.zh.core.page.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
//import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class SysUserServiceImpl implements SysUserService {

    private static final String RANKGNAME = "sys_user";

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysDeviceMapper sysDeviceMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserDeviceMapper sysUserDeviceMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysCollectMapper sysCollectMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysPointUnitMapper sysPointUnitMapper;

    //@Cacheable(value = "userList")
    @Override
    public List<SysUser> findAll() {
        List<SysUser> userList = sysUserMapper.findAll();
        return userList;
    }


  //  @Cacheable(value = "sysUser",key = "#username")
    @Override
    public SysUser findByName(String username) {
        return sysUserMapper.findByName(username);
    }

    @Override
    public SysUser findByNameWithId(String userName, Long id) {
        return sysUserMapper.findByNameWithId(userName,id);

    }

    @Transactional
    @Override
    public int save(SysUser record) {
        Long id = null;
        if(record.getId() == null || record.getId() == 0) {
            //添加用户
            sysUserMapper.insertUser(record);
            id=record.getId();
        }else{
            //修改用户
            sysUserMapper.updateByUser(record);
        }
        if(id != null && id == 0) {
            return 1;
        }
        if(id != null){
            for(SysUserRole sysUserRole:record.getUserRoles()){
                sysUserRole.setUserId(id);
            }
        }else{
            sysUserRoleMapper.deleteByUserId(record.getId());
        }
        for(SysUserRole sysUserRole:record.getUserRoles()){
            sysUserRoleMapper.insertUserRole(sysUserRole);
        }
        return 1;
    }

    @Override
    public int updatePassword(SysUser record){
        return sysUserMapper.updateByUser(record);
    }


    //   @CacheEvict(value = "sysUser")
    @Override
    public int delete(SysUser record) {
        Long id = record.getId();
            //根据用户id获取用户绑定的设备
        List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findForUserId(record.getId());
        if(!sysUserDevices.isEmpty()) {
            for (SysUserDevice sysUserDevice : sysUserDevices) {
                sysPointUnitMapper.deleteForUserDeviceId(sysUserDevice.getId());
                sysUserDeviceMapper.deleteByDevice(sysUserDevice.getId());
            }
        }
        //删除设备组,外键约束，同时删除了组变量
        List<SysCollect> sysCollects = sysCollectMapper.findPage(id);
        if(!sysCollects.isEmpty()){
            for(SysCollect sysCollect:sysCollects){
                sysCollectMapper.delete(sysCollect.getId());
            }
        }
        //删除用户角色绑定列表
        sysRoleMapper.deleteRoleForCreateId(id);
        //删除菜单列表
        sysMenuMapper.deleteMenuForCreateId(id);
        return sysUserMapper.deleteByUser(record.getId());
    }

    @Override
    public int delete(List<SysUser> records) {
        for(SysUser record:records){
            delete(record);
        }
        return 1;
    }

  //  @Cacheable(value = "sysUserById")
    @Override
    public SysUser findById(Long id) {
        SysUser sysUserById=sysUserMapper.findById(id);
        return sysUserById;
    }

  // @Cacheable(value = "pageResult")
    @Override
    public PageResult findPage(PageRequest pageRequest) {
        return MybatisPageHelper.findPage(pageRequest, sysUserMapper);
    }

  //  @Cacheable(value = "permiss",key ="#userName")
    @Override
    public Set<String> findPermissions(String userName){
        Set<String> perms = new HashSet<>();
        List<SysMenu> sysMenus = sysMenuService.findByUser(userName);
        for(SysMenu sysMenu:sysMenus) {
            if(sysMenu.getPerms() != null && !"".equals(sysMenu.getPerms())) {
                perms.add(sysMenu.getPerms());
            }
        }
        return perms;
    }

  //  @Cacheable(value = "findPageBy")
    @Override
    public PageResult findPageBy(PageRequest pageRequest) {
        PageResult pageResult=null;
        Object username = pageRequest.getParam("userName");
        Object name = pageRequest.getParam("name");
        //根据名称获取id
        SysUser sysUser = sysUserMapper.findByName((String) name);
        Long id = sysUser.getId();
        Map<Object, Object> params = new HashMap<>();
        params.put("uid",id);
        pageRequest.setParams(params);
        Object uid = pageRequest.getParam("uid");
        if(id == 1L){
            if(username!=null){
                pageResult = MybatisPageHelper.findPage(pageRequest, sysUserMapper, "findPageByAdmin", username);
            }else {
                 return MybatisPageHelper.findPage(pageRequest, sysUserMapper);
            }
        }else {
            if (username != null) {
                pageResult = MybatisPageHelper.findPage(pageRequest, sysUserMapper, "findPageByName", username, uid);
            } else {
                // return MybatisPageHelper.findPage(pageRequest, sysUserMapper);
                return MybatisPageHelper.findPage(pageRequest, sysUserMapper, "findPageById", uid);
            }
        }
        //加载用户角色信息
        findUserRoles(pageResult);
        return pageResult;
    }

    @Override
    public int upDevForUser(List<SysUserDevice> records,Long userId,Long selfId) {

     //   Long selfId  = sysUserService.getUserIdForSelf()
        //根据用户Id获取设备id列表
       List<SysUserDevice> sysDevices= sysUserDeviceMapper.findBUI(userId);
       boolean dr = sysDevices.isEmpty();
       List<String> ar = new ArrayList<>();           //要删除的设备集合
       List<String> br = new ArrayList<>();        //要添加的设备集合
        List<String> cr = new ArrayList<>();

        if(dr){                                     //如果该用户Id查询的UserDevice是空的，则进入
            for (int i =0;i<records.size()-1;i++){  //循环遍历设备上报要增加的UserDevice
                br.add(records.get(i).getDeviceIdent());        //写入增加的集合
            }
        }else if((records.size()-1) == 0){          //如果要增加的集合是空的
            for(SysUserDevice sysdes:sysDevices){   //循环遍历该用户Id查询的UserDevice
                ar.add(sysdes.getDeviceIdent());                 //写入删除集合
            }
        }
        else {
            for (int j =0;j<records.size()-1;j++) {     //否则遍历要增加的UserDevice
            for (SysUserDevice sysde : sysDevices) {        //遍历该Id下原有的UserDevice
                    if (sysde.getDeviceIdent().equals(records.get(j).getDeviceIdent())) {     //判断上报的deviceId与获取的查询的DeviceId是否相同
                        cr.add(records.get(j).getDeviceIdent());                 //相同则把上报的deviceId写入中间容器中
                    }
                }
            }
            for (int j =0;j<records.size()-1;j++) {             //将上报的deviceId写入增加集合中
                br.add(records.get(j).getDeviceIdent());
            }
            for (String f : cr) {                                 //将上报的与查询的，相同的移除
                br.remove(f);
            }
            for(SysUserDevice sysd : sysDevices){           //遍历要删除的
                ar.add(sysd.getDeviceIdent());
            }
            for(String u:cr){
                ar.remove(u);
            }

        }

        if(ar.size() != 0){
            for(String deviceIdent:ar) {

                //sysUserMapper.deleteUserDevice(userId, deviceIdent);
            }
        }
        if(br.size() != 0){

            for(String deviceIdent:br){
                SysUserDevice sysUserDevice = new SysUserDevice();
                sysUserDevice.setType(1L);
                sysUserDevice.setOrderNum(0L);
                sysUserDevice.setUserId(userId);
                sysUserDevice.setCreateId(selfId);
           //     sysUserDevice.setDeviceIdent(deviceIdent);
                sysUserDevice.setCreateTime(new Date());
               // sysUserDevice.setNickDeviceName("未定义昵称");
                List<SysUserDevice> sysUserDevicesList = sysUserDeviceMapper.findByUserId(selfId);
                for(SysUserDevice sud1:sysUserDevicesList){
                    if(sud1.getDeviceIdent().equals(deviceIdent)){
                        //根据设备Id获取设备名称
                        String ident=sud1.getDeviceIdent();
                        SysUserDevice sysU = sysUserDeviceMapper.findBDI(selfId,ident);
                        sysUserDevice.setNickDeviceName(sysU.getNickDeviceName());
                        sysUserDevice.setParentDeviceId(sysU.getParentDeviceId());
                    }
                }
                SysUserDevice sysUserDevice2 = sysUserDeviceMapper.findBDI(selfId,deviceIdent);
              // String deviceIdent=sysDevice.getIdent();
                sysUserDevice.setDeviceIdent(sysUserDevice2.getDeviceIdent());
                sysUserDevice.setPointNums(sysUserDevice2.getPointNums());
                sysUserMapper.insertUserDevice(sysUserDevice);
            }
        }
        return 1;
    }
/*
    public static void main (String[] args){
        Long[] a = {1L,2L,3L,4L};             //
        Long[] b= {1L};
        List<Long> ar = new ArrayList<>();           //a在b中没有的数组---3L           需要删除的
        List<Long> br= new ArrayList<>();           //b在a中没有的数组    ----4L,5L        需要增加的
        List<Long> cr = new ArrayList<>();
        for(int i=0;i<a.length;i++){
            for(int j=0;j<b.length;j++){
                System.out.println(a[i]+"---"+b[j]);
                if(a[i]==b[j]){
                    ar.add(a[i]);
                    System.out.println(ar);     //1L 2L
                }
            }
        }
        for(int i=0;i<a.length;i++){
            br.add(a[i]);
            System.out.println(br);     //1 2 4 5
        }
        for(Long f:ar){
            br.remove(f);
            System.out.println(br);
        }
        for(int j=0;j<b.length;j++){
            cr.add(b[j]);
        }
        for(Long u:ar){
            cr.remove(u);
        }

        Object[] e = br.toArray();
        Object[] r =cr.toArray();
        System.out.println(Arrays.toString(e));     //4L\5L
        System.out.println(Arrays.toString(r));         //1L\2L     ---3L
    }*/

  //  @Cacheable(value = "userRoleList",key = "#userId")
    @Override
    public List<SysUserRole> findUserRoles(Long userId) {

        return sysUserRoleMapper.findUserRoles(userId);
    }


    /**
     * 加载用户角色
     * @param pageResult
     */
    private void findUserRoles(PageResult pageResult){
        List<?> content = pageResult.getContent();
        for(Object object:content){
            SysUser sysUser = (SysUser) object;
            List<SysUserRole> userRoles = findUserRoles(sysUser.getId());
            sysUser.setUserRoles(userRoles);
            sysUser.setRoleName(getRoleName(userRoles));
        }
    }

    private String getRoleName(List<SysUserRole> userRoles){
        StringBuilder sb = new StringBuilder();
        for (Iterator<SysUserRole> iter = userRoles.iterator();iter.hasNext();){
            SysUserRole userRole = iter.next();
            SysRole sysRole =sysRoleMapper.findRoleById(userRole.getRoleId());
            if(sysRole == null){
                continue ;
            }
            sb.append(sysRole.getRemark());
            if(iter.hasNext()){
                sb.append(", ");
            }
        }
        return sb.toString();
    }

}
